package enote.view;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.URL;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.part.ViewPart;

public class NoteView extends ViewPart {

	/** the plug-in id from plugin.xml */
	public static final String ID = "enote.view.NoteView";

	/** the file instance where to load and store the text */
	private final File file;

	/** the text component in the view */
	private Text note;

	public NoteView() {
		URL url = Platform.getInstanceLocation().getURL();
		file = new File(url.getPath() + "eNotePlugin.txt");
	}

	/** this method is called when the View is created */
	public void createPartControl(Composite parent) {
		Font editorFont = null;
		try {
			// try to take the default font for editor components
			editorFont = JFaceResources.getTextFont();
		} catch (Throwable e) {
			// if there is a problem with taking the font use this one
			editorFont = new Font(Display.getDefault(), "Courier New", 10, SWT.NORMAL);
		}
		note = new Text(parent, SWT.MULTI | SWT.BORDER | SWT.WRAP | SWT.V_SCROLL | SWT.BORDER);
		note.setText(readFile(file));
		note.setFont(editorFont);
		note.addListener(SWT.Dispose, new Listener() {
			public void handleEvent(Event event) {
				NoteView.writeFile(file, note.getText());
			}

		});
	}

	/**
	 * Define focus to be on the Note component
	 */
	public void setFocus() {
		note.setFocus();
	}

	/**
	 * Reads a file content as UTF8 encoded string
	 * 
	 * @param file
	 *            the file to read from
	 * @return the file content
	 */
	static String readFile(File file) {
		StringBuffer buffer = new StringBuffer();
		try {
			FileInputStream fis = new FileInputStream(file);
			InputStreamReader isr = new InputStreamReader(fis, "UTF8");
			Reader in = new BufferedReader(isr);
			int ch;
			while ((ch = in.read()) > -1) {
				buffer.append((char) ch);
			}
			in.close();
		} catch (Exception e) {}
		return buffer.toString();
	}

	/**
	 * Saves a string in file as utf8 encoding
	 * 
	 * @param file
	 *            the file to write to
	 * @param str
	 *            the string to be stored
	 */
	static void writeFile(File file, String str) {
		try {
			FileOutputStream fos = new FileOutputStream(file);
			Writer out = new OutputStreamWriter(fos, "UTF8");
			out.write(str);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
